'''
It is need to build some scripts to invoke remote client to connect the server
To test the resource requirement for 7 AI players with increasing number(1 to 4)  of the Speculator players who doesnt play just watch.
This is only a local test, need to improve it to invoke remotely clients
'''
import Process,os, sys,time, string, DB, Analysis
from Configuration import Configuration
from Performance import Performance
if __name__ == "__main__":
    if len(sys.argv) < 8:
        print "This script need at least 2 parameters: \"client\" , serverIP, expId, turn, factor, maxYear, clientIp"
    else:
        expName = "1c"
        Configuration.initExp(expName)
        Configuration.mkExpDir(expName)
        path = os.path.join("..","test_result")
        f = open(os.path.join(path, "networkName"),"a")
        log = open(os.path.join(path, "log"),"a")
        
        measurement = Performance()
        measurement.flag = 1
        measurement.start()
#        print sys.argv
        expId = string.atoi(sys.argv[3])
        turn = string.atoi(sys.argv[4])
        factor = string.atoi(sys.argv[5])
        Process.maxYear = string.atoi(sys.argv[6])
        selfIp = sys.argv[7]
        
        print >> log, "1c_client"    
        print >>log,"turn%d"%turn, factor
        filename = "test1c" + "_result_"+"%d"%turn+"_%d"%factor +".txt"
        file = open(os.path.join(path, expName,filename), "w")
        starttime = time.time()
        print >> file, "-----------" + time.asctime() + "-----------\n" + "%f"%starttime
        print >> file, "%d_"%turn+ " clients %d"%factor
        
        if sys.argv[1] == "client":
            if sys.platform == "win32":
                os.system("test1c.bat")
            else :
                os.system("openttd -g -n " + sys.argv[2] + "&")
        
        Process.killOpenTTD(file)
        endtime = time.time()
        print >> file,"%f"%endtime + "\n-----------" + time.asctime() + "-----------\n"
        print >> log,"%f"%endtime + "\n-----------" + time.asctime() + "-----------\n"
        file.flush()
        savefilename = "%d"%expId + "_" + expName + "_%d"%turn + "_%d_"%factor + selfIp
        DB.type = 1
        DB.insert(expId, expName, turn, factor, starttime, endtime, -1.0, Process.maxYear, savefilename)
        measurement.save()
        try:
            Analysis.updateSkipList(Process.maxYear)
            Analysis.analysisCPUandMemSingleFile(expId, expName, turn, factor, filename, savefilename + "_cpu.txt")
        except Exception:
            pass